﻿using System.ServiceModel;
using System.ServiceModel.Description;
using System.Windows.Browser;
using Ninject.Core;
using Odin.Silverlight.RemoteSessionManager;

namespace Odin.Silverlight.Modules
{
	public class ServiceModule : StandardModule
	{
		private static void SetAddressForService(ICommunicationObject service, string baseAddress)
		{
			var endpointProperty = service.GetType().GetProperty("Endpoint");
			if (null != endpointProperty)
			{
				var endPoint = endpointProperty.GetValue(service, null) as ServiceEndpoint;

				if (null != endPoint)
				{
					var newUri = string.Format("{0}{1}", baseAddress, endPoint.Address.Uri.AbsolutePath);
					endPoint.Address = new EndpointAddress(newUri);
				}
			}
		}

		private static string GetBaseUrl()
		{
			var uri = HtmlPage.Document.DocumentUri;
			var url = string.Format("{0}://{1}:{2}",
			              uri.Scheme,
			              uri.Host,
			              uri.Port
				);
			return url;
		}

		public override void Load()
		{
			var baseUrl = GetBaseUrl();

			var remoteSessionManagerService = new RemoteSessionManagerClient();
			SetAddressForService(remoteSessionManagerService,baseUrl);
			Bind<IRemoteSessionManager>().ToConstant(remoteSessionManagerService);
		}
	}
}
